<template>
  <div class="no-background-container">
    <!-- 搜索表单 -->
    <search-form-qvil
      v-model="queryForm"
      :affixed="true"
      :fields="searchFields"
      :inline="true"
      :loading="listLoading"
      :show-label="false"
      @form-change="updateQueryForm"
      @reset="resetQueryForm"
      @search="queryData"
    >
      <template #actions>
        <el-button type="primary" @click="getList">
          <el-icon><refresh /></el-icon>
          刷新
        </el-button>
      </template>
    </search-form-qvil>

    <!-- 表格 -->
    <table-qvil
      v-model:page="queryForm.page"
      v-model:page-size="queryForm.limit"
      :border="true"
      :columns="tableColumns"
      :data="tableData"
      :loading="listLoading"
      :show-index="true"
      :stripe="true"
      :total="total"
      @page-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
      <!-- 审核内容列 -->
      <template #column-content="{ row }">
        <div>{{ row.content }}</div>
      </template>

      <!-- 提交人列 -->
      <template #column-user="{ row }">
        <div>{{ row.user?.name || '-' }}</div>
      </template>

      <!-- 审核人列 -->
      <template #column-reviewerUser="{ row }">
        <div>{{ row.reviewerUser?.name || '-' }}</div>
      </template>

      <!-- 状态列 -->
      <template #column-status="{ row }">
        <el-tag
          :type="
            row.status === ENUM_EXAMINE_APPROVE_STATUS.审核通过
              ? 'success'
              : row.status === ENUM_EXAMINE_APPROVE_STATUS.审核不通过
                ? 'danger'
                : row.status === ENUM_EXAMINE_APPROVE_STATUS.审核中
                  ? 'warning'
                  : 'info'
          "
        >
          {{ statusMap[row.status] || row.status || '-' }}
        </el-tag>
      </template>

      <!-- 操作列 -->
      <template #column-operation="{ row }">
        <div class="operations-container">
          <el-button v-if="row.status === ENUM_EXAMINE_APPROVE_STATUS.审核中" size="small" text type="primary" @click="handleCheck(row)">
            <el-icon class="button-icon"><check /></el-icon>
            审核
          </el-button>
          <el-button size="small" text type="info" @click="handleDetail(row)">
            <el-icon class="button-icon"><info-filled /></el-icon>
            详情
          </el-button>
          <!-- <el-button size="small" text type="danger" @click="handleDelete(row)">
            <el-icon class="button-icon"><delete /></el-icon>
            删除
          </el-button> -->
        </div>
      </template>

      <!-- 空数据插槽 -->
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </table-qvil>

    <!-- 详情弹窗 -->
    <detail-dialog-qvil
      v-model="showDetailDialog"
      :detail-data="currentRow || {}"
      :fields="detailFields"
      :loading="false"
      title="审批详情"
      @close="currentRow = undefined"
    >
      <template v-if="currentRow?.status === ENUM_EXAMINE_APPROVE_STATUS.审核中" #footer>
        <el-button type="primary" @click="handleCheck(currentRow)">审核</el-button>
      </template>
    </detail-dialog-qvil>

    <!-- 审核弹窗 -->
    <form-dialog-qvil
      v-model="showCheckDialog"
      :confirm-loading="checkLoading"
      :fields="checkFormFields"
      :form-data="checkForm"
      title="审核确认"
      @cancel="showCheckDialog = false"
      @confirm="submitCheck"
    />
  </div>
</template>

<script lang="ts" setup>
import { Check, InfoFilled, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { checkFormFields, detailFields, searchFields, statusMap, tableColumns } from './config'
import * as examineApi from '/@/api/examine'
import { ENUM_EXAMINE_APPROVE_STATUS } from '/@/api/examine/types'

const tableData = ref<any[]>([])
const listLoading = ref(false)
const total = ref(0)

// 当前选中的行数据
const currentRow = ref<any>()
const showDetailDialog = ref(false)

// 审核相关
const showCheckDialog = ref(false)
const checkLoading = ref(false)
const checkForm = ref({
  status: ENUM_EXAMINE_APPROVE_STATUS.审核通过,
  remark: '',
  repetitionCheck: '',
})

interface QueryForm {
  page: number
  limit: number
  type?: string
  status?: ENUM_EXAMINE_APPROVE_STATUS
  [key: string]: any
}

const queryForm = ref<QueryForm>({
  page: 1,
  limit: 20,
  activityId: localStorage.getItem('hongyouActId'),
})

// 获取列表数据
const getList = async () => {
  listLoading.value = true
  try {
    const data = await examineApi.getExamineList(queryForm.value)
    if (data?.code === 0) {
      tableData.value = data.result.rows || []
      total.value = data.result.count || 0
    } else {
      ElMessage.error(data?.message || '获取数据失败')
    }
  } catch (error: any) {
    console.error(error)
    ElMessage.error(error?.message || '获取数据失败')
  } finally {
    listLoading.value = false
  }
}

// 查看详情
const handleDetail = async (row: any) => {
  try {
    const data = await examineApi.getExamineDetail(row.id)
    if (data?.code === 0) {
      currentRow.value = data.result
      showDetailDialog.value = true
    } else {
      ElMessage.error(data?.message || '获取详情失败')
    }
  } catch (error: any) {
    console.error(error)
    ElMessage.error(error?.message || '获取详情失败')
  }
}

// 打开审核弹窗
const handleCheck = async (row: any) => {
  currentRow.value = row
  checkForm.value = {
    status: ENUM_EXAMINE_APPROVE_STATUS.审核通过,
    remark: '',
    repetitionCheck: '',
  }
  showCheckDialog.value = true
}

// 提交审核
const submitCheck = async (formDataFromDialog: Record<string, any>) => {
  if (!currentRow.value) return
  console.log('Submitting data from dialog:', JSON.parse(JSON.stringify(formDataFromDialog)))
  try {
    checkLoading.value = true
    const data = await examineApi.checkExamineH5({
      id: currentRow.value.id,
      status: formDataFromDialog.status,
      remark: formDataFromDialog.remark || '审核意见',
      repetitionCheck: formDataFromDialog.repetitionCheck,
    })

    if (data?.code === 0) {
      ElMessage.success('操作成功')
      showCheckDialog.value = false
      showDetailDialog.value = false
      await getList()
    } else {
      ElMessage.error(data?.message || '操作失败')
    }
  } catch (error: any) {
    console.error(error)
    ElMessage.error(error?.message || '操作失败')
  } finally {
    checkLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  queryForm.value.limit = size
  queryForm.value.page = 1
  getList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  queryForm.value.page = page
  getList()
}

// 查询数据
const queryData = () => {
  queryForm.value.page = 1
  getList()
}

// 更新查询表单
const updateQueryForm = (newForm: Partial<QueryForm>) => {
  queryForm.value = { ...queryForm.value, ...newForm }
}

// 重置查询表单
const resetQueryForm = () => {
  queryForm.value = {
    page: 1,
    limit: 20,
    activityId: localStorage.getItem('hongyouActId'),
  }
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.no-background-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 0 1.25rem 1.25rem;
  background-color: var(--el-bg-color);
}
.operations-container {
  @apply whitespace-nowrap flex gap-2;
}

.button-icon {
  @apply mr-1 align-middle;
}
</style>
